package com.edu.employee.controller.test;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ProjectName: summer-project
 * @Titile: LoginFilter
 * @Author: Lucky
 * @Description: TODO
 */
//urlPatterns：匹配的url;filterName:过滤器的逻辑名称
@WebFilter(urlPatterns = "/api/**",filterName = "loginFilter")
public class LoginFilter implements Filter {
    /**
     * 过滤器初始化方法
     * web容器一启动，这个方法就要执行
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 过滤器的过滤方法
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response  = (HttpServletResponse) servletResponse;
        //获取用户信息
        Object user = request.getSession().getAttribute("user");
        if(user==null){
            // 处理的逻辑代码
            //如果需要被拦截
            //转发
            //request.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
            //重定向
            response.sendRedirect("login.jsp");
        }else{
            //如果是放行
            filterChain.doFilter(servletRequest,servletResponse);
        }




    }

    /**
     * 摧毁方法
     * 在web容器被摧毁前，这个方法要被执行
     */
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
